package com.test.platform.controller;

import com.test.platform.model.PublishInfo;
import com.test.platform.service.publish.PublishInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;    
import org.slf4j.LoggerFactory; 
import java.util.Map;
import java.util.List;
import java.util.ArrayList; 

@RestController
@RequestMapping("/api/publish-info")
public class PublishInfoController {
    
    private static final Logger logger = LoggerFactory.getLogger(PublishInfoController.class);
    
    @Autowired
    private PublishInfoService publishInfoService;
    
    @GetMapping
    public ResponseEntity<List<PublishInfo>> getAllPublishInfos() {
        return ResponseEntity.ok(publishInfoService.getAllPublishInfos());
    }
    
    @GetMapping("/{id}")
    public ResponseEntity<PublishInfo> getPublishInfoById(@PathVariable Integer id) {
        PublishInfo publishInfo = publishInfoService.getPublishInfoById(id);
        if (publishInfo != null) {
            return ResponseEntity.ok(publishInfo);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    @GetMapping("/search/owner")
    public ResponseEntity<List<PublishInfo>> findByOwner(@RequestParam String owner) {
        List<PublishInfo> publishInfos = publishInfoService.findByOwner(owner);
        return ResponseEntity.ok(publishInfos);
    }

    @GetMapping("/search/name")
    public ResponseEntity<List<PublishInfo>> findByName(@RequestParam String name) {
        List<PublishInfo> publishInfos = publishInfoService.findByName(name);
        return ResponseEntity.ok(publishInfos);
    }

    // 修改现有的搜索方法
    @GetMapping("/search")
    public ResponseEntity<List<PublishInfo>> findByOwnerAndName(
            @RequestParam(required = false) String owner,
            @RequestParam(required = false) String name) {
        List<PublishInfo> publishInfos;
        if (owner != null && name != null) {
            publishInfos = publishInfoService.findByOwnerAndName(owner, name);
        } else if (owner != null) {
            publishInfos = publishInfoService.findByOwner(owner);
        } else if (name != null) {
            publishInfos = publishInfoService.findByName(name);
        } else {
            publishInfos = publishInfoService.getAllPublishInfos();
        }
        return ResponseEntity.ok(publishInfos);
    }

    @GetMapping("/update-status")
    public ResponseEntity<Boolean> getUpdateStatus() {
        try {
            return ResponseEntity.ok(publishInfoService.isUpdateEnabled());
        } catch (Exception e) {
            logger.error("获取更新状态失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                               .body(false);
        }
    }

    @PostMapping
        public ResponseEntity<?> createPublishInfo(@RequestBody PublishInfo publishInfo) {
            try {
                logger.info("接收到创建发布信息请求: {}", publishInfo);
                boolean result = publishInfoService.createPublishInfo(publishInfo);
                if (result) {
                    return ResponseEntity.ok().body(Map.of("success", true));
                } else {
                    return ResponseEntity.badRequest().body(Map.of(
                        "success", false,
                        "message", "创建发布信息失败"
                    ));
                }
            } catch (Exception e) {
                logger.error("创建发布信息时发生错误", e);
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                                   .body(Map.of(
                                       "success", false,
                                       "message", "服务器内部错误：" + e.getMessage()
                                   ));
            }
        }

    @PutMapping("/{id}")
    public ResponseEntity<?> updatePublishInfo(@PathVariable Integer id, @RequestBody PublishInfo publishInfo) {
        try {
            logger.info("接收到更新发布信息请求: id={}, data={}", id, publishInfo);
            publishInfo.setId(id);  // 确保设置正确的ID
            boolean result = publishInfoService.updatePublishInfo(publishInfo);
            if (result) {
                return ResponseEntity.ok().body(Map.of("success", true));
            } else {
                return ResponseEntity.badRequest().body(Map.of(
                    "success", false,
                    "message", "更新发布信息失败"
                ));
            }
        } catch (Exception e) {
            logger.error("更新发布信息时发生错误", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                               .body(Map.of(
                                   "success", false,
                                   "message", "服务器内部错误：" + e.getMessage()
                               ));
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<?> deletePublishInfo(@PathVariable Integer id) {
        try {
            logger.info("接收到删除发布信息请求: id={}", id);
            boolean result = publishInfoService.deletePublishInfo(id);
            if (result) {
                return ResponseEntity.ok().body(Map.of("success", true));
            } else {
                return ResponseEntity.badRequest().body(Map.of(
                    "success", false,
                    "message", "删除发布信息失败"
                ));
            }
        } catch (Exception e) {
            logger.error("删除发布信息时发生错误", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                               .body(Map.of(
                                   "success", false,
                                   "message", "服务器内部错误：" + e.getMessage()
                               ));
        }
    }

    @PostMapping("/publish")
    public ResponseEntity<?> publishInfo(@RequestBody Map<String, String> request) {
        try {
            String owner = request.get("owner");
            String name = request.get("name");
            logger.info("接收到发布请求: owner={}, name={}", owner, name);
            
            boolean result = publishInfoService.publish(owner, name);
            // 根据不同状态返回不同的消息类型
            if (result) {
                return ResponseEntity.ok().body(Map.of(
                    "success", true,
                    "message", "ohpm SUCCESS",
                    "shouldClose", true
                ));
            } else {
                return ResponseEntity.badRequest().body(Map.of(
                    "success", false,
                    "message", "ohpm ERROR",
                    "shouldClose", false
                ));
            }
        } catch (Exception e) {
            logger.error("发布过程中发生错误", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                               .body(Map.of(
                                   "success", false,
                                   "message", "ohpm ERROR: " + e.getMessage(),
                                   "shouldClose", false
                               ));
        }
    }

    @PostMapping("/batch-publish")
    public ResponseEntity<?> batchPublish(@RequestBody List<Map<String, String>> publishItems) {
        try {
            logger.info("接收到批量发布请求: {}", publishItems);
            // 为每个项目单独处理发布
            List<Map<String, Object>> results = new ArrayList<>();
            for (Map<String, String> item : publishItems) {
                try {
                    String owner = item.get("owner");
                    String name = item.get("name");
                    boolean itemResult = publishInfoService.publish(owner, name);
                    results.add(Map.of(
                        "owner", owner,
                        "name", name,
                        "success", itemResult,
                        "message", itemResult ? "ohpm SUCCESS" : "ohpm ERROR",
                        "shouldClose", false  // 允许用户手动关闭
                    ));
                } catch (Exception e) {
                    results.add(Map.of(
                        "owner", item.get("owner"),
                        "name", item.get("name"),
                        "success", false,
                        "message", "ohpm ERROR: " + e.getMessage(),
                        "shouldClose", false  // 允许用户手动关闭
                    ));
                }
            }
            return ResponseEntity.ok().body(Map.of(
                "results", results,
                "success", true
            ));
        } catch (Exception e) {
            logger.error("批量发布过程中发生错误", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                               .body(Map.of(
                                   "success", false,
                                   "message", "ohpm ERROR: " + e.getMessage(),
                                   "shouldClose", false  // 允许用户手动关闭
                               ));
        }
    }
}